package it.intecs.pisa.smarcos.activities;

import it.intecs.pisa.smarcos.R;
import it.intecs.pisa.smarcos.base.GestureEvents;
import it.intecs.pisa.smarcos.base.GestureIntents;
import it.intecs.pisa.smarcos.base.SpeechManager;
import it.intecs.pisa.smarcos.base.XMLParser;
import it.intecs.pisa.smarcos.services.HumanInteractionService;
import it.intecs.pisa.smarcos.util.ContextUtils;
import it.intecs.pisa.smarcos.util.MathUtils;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

 
public class MenuNavigation extends BaseActivity {
	
	public static final String INTENT_SHOW="it.intecs.pisa.smarcos.activities.MenuNavigation.SHOW";
	private static final String TAG = MenuNavigation.class.getSimpleName();
	private static final String WHERE_RETURN = HumanInteractionService.TAG;
		
	private SpeechManager speechManager;
	private XMLParser parser;
	
	View view; 
	private Vibrator vibrator;
	private ViewGroup baseCenterView;
	private ContextUtils cUtils;
	private String position;
	
	float startX,startY;
	
	LayoutInflater inflater;
	private LayoutUpdater layoutUpdater;
	private IntentFilter layoutFilter;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Log.d(TAG, "OnCreate");

		speechManager = SpeechManager.getInstance(getApplicationContext());
		parser = XMLParser.getInstance(null, null);
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		cUtils = new ContextUtils(getApplicationContext());
		
		// Metodo di BaseViewManager
		Init(getBaseContext());
		setA(R.string.NAV_Button_A_Close);
		setC(R.string.NAV_Button_End);
		setD(R.string.NAV_Button_End);
		
		inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
		view = inflater.inflate(cUtils.retrieveRvalue("layout", parser.getAttributeValue(getString(R.string.MENU_ATTR_L2V))), null);
		setContentView(getBaseView());
		baseCenterView = (ViewGroup) findViewById(R.id.center_base_view);
		baseCenterView.addView(view);
			
		position = getString(R.string.MV_Main_Menu); 
		
		// TtsReadyReceiver filter
		layoutFilter = new IntentFilter();
		layoutFilter.addAction("Update View");
		layoutFilter.addAction("Update Background");
		layoutFilter.addCategory(Intent.CATEGORY_DEFAULT);
		layoutUpdater = new LayoutUpdater();
		
		registerReceiver(layoutUpdater, layoutFilter);
	}

	@Override
	public void onResume() {
		super.onResume();

		Log.d(TAG, "onResume");
			
		passBy = false;
		if(position != null)
			speechManager.say(position, false, false);	
	
		//Log.d(TAG, "Base View " + baseView.getView().getLeft() + " " + baseView.getView().getTop()
			//	+ " " + baseView.getView().getBottom() + " " + baseView.getView().getRight());
		//registerReceiver(layoutUpdater, layoutFilter);
	}
	
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "OnDestroy");
		unregisterReceiver(layoutUpdater);
	}

	
	// BACK - CLOSE
	@Override
	public void onClick_A(){
		Log.d(TAG, "onClick_A");
		vibrator.vibrate(100);
		Intent intent;
		if (position.equals(getString(R.string.MV_Main_Menu))){
			intent=new Intent("CLOSE SERVICE");
			intent.addCategory(Intent.CATEGORY_DEFAULT);
			sendBroadcast(intent);
			finish();	
		}else{	
			intent=new Intent(HumanInteractionService.TAG + GestureIntents.INTENT_GESTURE_UP);
			intent.addCategory(Intent.CATEGORY_DEFAULT);
			sendBroadcast(intent);	
		}
	}
	
	// POSITION
	@Override
	public void onClick_B(){
		Log.d(TAG, "onClick_B");
		vibrator.vibrate(100);
		if(position != null)
			speechManager.say(position, false, false);	
	}
	
	// NOT ACTIVE
	@Override
	public void onClick_C(){
		Log.d(TAG, "onClick_C");
		vibrator.vibrate(100);
		
		Intent intent;
		if (!position.equals(getString(R.string.MV_Main_Menu))){
	
			intent=new Intent(HumanInteractionService.TAG + GestureIntents.INTENT_GESTURE_UP_MAIN);
			intent.addCategory(Intent.CATEGORY_DEFAULT);
			sendBroadcast(intent);	
		}
		
	}

	// NOT ACTIVE
	@Override
	public void onClick_D(){
		Log.d(TAG, "onClick_D");
		//vibrator.vibrate(100);
		onClick_C();
	}


	@Override
		public void onClick_Center(int event, float X, float Y){
			
			Log.d(TAG, "onClick_Center");
			
			float lenghtTreshold=10;
			
			switch(event)
			{
				case GestureEvents.ONFLING_START:
	
					startX = X;
					startY = Y;
					break;

				case GestureEvents.ONFLING_STOP:

					float endX,endY;

					endX = X;
					endY = Y;

					float gestureLenght=0;

					gestureLenght=MathUtils.distanceBetweenPoints(endX,startX,endY,startY);

					if(gestureLenght>lenghtTreshold){

						String gesture = MathUtils.calculateSlice(endX,startX,endY,startY);
						if (gesture.length() != 0)
							fireIntent(gesture);
					}
					break;

				case GestureEvents.ONDOUBLETAP:
					fireIntent(GestureIntents.INTENT_GESTURE_SELECT);
					break;

				case GestureEvents.ONSCROLL:
					if (passBy == true)
						speechManager.say(position, false, false);
					break;
			}
	}

	private View createNotificationView(){
		
		int i;
		int numOfNotifications = parser.getNumOfNotification();
		String message;
		View view;
		view = inflater.inflate(R.layout.menu_notification, null);
		LinearLayout linear = (LinearLayout) view.findViewById(R.id.notification_menu_view);
		for (i=0; i<numOfNotifications ; i++){

			TextView tView = new TextView(this);
			int id = MathUtils.convertToInteger((parser.getEntryToLightUp(i)).substring(12));
			tView.setId(id);
			message = parser.getNotificationMessage(i);
			tView.setText(message);
			tView.setTextColor(R.color.LTBLUE);
			tView.setTextSize(TypedValue.COMPLEX_UNIT_PT, 11);
			tView.setGravity(1);
			LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
			layoutParams.weight = 1;
			linear.addView(tView, layoutParams);
		}
	
		return view;
	}

		
	private class LayoutUpdater extends BroadcastReceiver {

		private final String TAG = LayoutUpdater.class.getSimpleName();

		@Override
		public void onReceive(Context arg0, Intent intent) {

			int id;
			String action = intent.getAction();
			Log.d(TAG, action);
			
			/*if (action.equals("Update View")){

				String step = intent.getStringExtra("Step");
				Log.d(TAG, step);
				if (step.equals("Notification Root") && parser.isRootNode()){
					// Aggiunta o cancellazione della voce Notifications nel menu principale
					id = cUtils.retrieveRvalue("layout", intent.getStringExtra("layoutToView"));
					view = inflater.inflate(id, null);	
					position = getString(R.string.MV_Main_Menu);
				}

				if (step.equals("Notification Element") && (parser.getAttributeValue("type")).equals("Notification"))
					view = createNotificationView();

				if (step.equals("Standard")){
					position = getString(cUtils.retrieveRvalue("string", (parser.getAttributeValue(getString(R.string.MENU_ATTR_S2SM))).substring(8)));
					if ((parser.getAttributeValue("type")).equals("Notification"))
						view = createNotificationView();
					else{
						id = cUtils.retrieveRvalue("layout", parser.getAttributeValue(getString(R.string.MENU_ATTR_L2V)));
						view = inflater.inflate(id, null);
					}
				}

				if (position.equals(getString(R.string.MV_Main_Menu)))
					setA(R.string.NAV_Button_A_Close);
				else
					setA(R.string.NAV_Button_A_Back);
				
				baseCenterView.removeAllViews();
				baseCenterView.addView(view);
			}*/

			if (action.equals("Update View")){

				position = getString(cUtils.retrieveRvalue("string", (parser.getAttributeValue(getString(R.string.MENU_ATTR_S2SM))).substring(8)));
				if ((parser.getAttributeValue("type")).equals("Notification"))
					view = createNotificationView();
				else{
					id = cUtils.retrieveRvalue("layout", parser.getAttributeValue(getString(R.string.MENU_ATTR_L2V)));
					view = inflater.inflate(id, null);
				}

				if (position.equals(getString(R.string.MV_Main_Menu)))
					setA(R.string.NAV_Button_A_Close);
				else
					setA(R.string.NAV_Button_A_Back);

				baseCenterView.removeAllViews();
				baseCenterView.addView(view);
			}

			if (action.equals("Update Background")){

				id = intent.getIntExtra("Id", 12);
				TextView textView = (TextView)findViewById(id);
				int color = intent.getIntExtra("Color", 0);
				textView.setTextColor(color);
			}
		}
	}
	
	
	protected void fireIntent(String action)
	{
		Intent intent;
		intent=new Intent(WHERE_RETURN + action);
		intent.addCategory(Intent.CATEGORY_DEFAULT);
		
		sendBroadcast(intent);
	}
}
